<?php
/**
 * 用户收货地址接口
 * @author maniac
 */
namespace app\api\controller\v1;

use app\facade\MemberAddresses AS MemberAddressesFacade;

class MemberAddresses extends Base
{
    /**
     * 获取用户默认收货地址
     */
    public function defAddr()
    {
        $userId = $this->checkUserToken();

        try {
            $info = MemberAddressesFacade::defAddr($userId);
            return j(0, '获取收货地址成功', $info);
        } catch (\Exception $e) {
            return j(1, $e->getMessage());
        }
    }
    
    /**
     * 设置用户默认收货地址
     */
    public function setDefAddr()
    {

        $userId = $this->checkUserToken();
        $id     = input('post.id/d', 0);
        try {
            $info = MemberAddressesFacade::setDefAddr($userId, $id);
            return j(0, '设置收货地址成功', $info);
        } catch (\Exception $e) {
            return j(1, $e->getMessage());
        }
    }
    
    /**
     * 获取用户收货地址信息
     */
    public function addresses()
    {
        $userId = $this->checkUserToken();
        $id     = input('post.id/d', 0);
        try {
            $data = MemberAddressesFacade::addresses($userId);
            if ($id) {
                $data = MemberAddressesFacade::address($userId, $id);
            }
            return j(0, '获取信息成功', $data);
        } catch (\Exception $e) {
            return j(1, $e->getMessage());
        }
    }
    
    /**
     * 编辑用户收货地址
     */
    public function editAddress()
    {

        $userId = $this->checkUserToken();
        $post   = input('post.');
        $post['userid'] = $userId;
        if (!$post['name'] || !$post['mobile'] || !$post['province'] || !$post['city'] || !$post['district'] || !$post['address']) {
            return j(1, '地址信息不完整');
        }
        if (!preg_match('/^1\d{10}$/', $post['mobile'])) {
            return j(1, '请输入正确的手机号');
        }
        try {
            $data = MemberAddressesFacade::editAddress($post);
            return j(0, '成功', $data);
        } catch (\Exception $e) {
            return j(1, $e->getMessage());
        }
    }
    
    /**
     * 删除用户收货地址
     */
    public function delAddress()
    {
        $userId = $this->checkUserToken();
//        $userId = input('user_id');
        $id     = input('post.id/d', 0);
        try {
            $info = MemberAddressesFacade::delAddress($id, $userId);
            return j(0, '删除收货地址成功', $info);
        } catch (\Exception $e) {
            return j(1, $e->getMessage());
        }
    }
}
